<template>
  <div class="goodshow-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>货品信息</h2>
      <p>货品信息查询与管理</p>
    </div>

    <!-- 查询条件 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="货品名称">
          <el-input
            v-model="searchForm.goodName"
            placeholder="请输入货品名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="货品状态">
          <el-select
            v-model="searchForm.goodState"
            placeholder="请选择状态"
            clearable
            style="width: 150px"
          >
            <el-option label="全部" :value="null" />
            <el-option label="上架" :value="1" />
            <el-option label="下架" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <el-card class="action-card" shadow="never">
      <div class="action-buttons">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增货品
        </el-button>
        <el-button type="success" @click="handleExport">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <el-table 
        :data="tableData" 
        v-loading="loading" 
        stripe 
        border 
        style="width: 100%"
        :height="600"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="goodCode" label="货品编码" width="120" />
        <el-table-column prop="goodName" label="货品名称" width="150" show-overflow-tooltip />
        <el-table-column prop="specification" label="规格" width="100" />
        <el-table-column prop="company" label="生产厂家" width="120" show-overflow-tooltip />
        <el-table-column prop="rprice" label="进价" width="100">
          <template #default="{ row }">
            <span class="price-text">¥{{ row.rprice }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="cprice" label="售价" width="100">
          <template #default="{ row }">
            <span class="price-text">¥{{ row.cprice }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="supplierName" label="供应商" width="120" show-overflow-tooltip />
        <el-table-column prop="supplierLevel" label="供应商等级" width="100" />
        <el-table-column prop="people" label="联系人" width="100" />
        <el-table-column prop="phone" label="联系电话" width="120" />
        <el-table-column prop="customerName" label="客户" width="100" show-overflow-tooltip />
        <el-table-column prop="customerType" label="客户类型" width="100" />
        <el-table-column prop="goodState" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStateTagType(row.goodState)" effect="dark">
              {{ getStateText(row.goodState) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button type="primary" size="small" @click="handleDetail(row)">
                <el-icon><InfoFilled /></el-icon>
                详情
              </el-button>
              <el-button 
                :type="row.goodState === 1 ? 'warning' : 'success'" 
                size="small" 
                @click="handleToggleStatus(row)"
              >
                <el-icon><Switch /></el-icon>
                {{ row.goodState === 1 ? '下架' : '上架' }}
              </el-button>
              <el-button type="warning" size="small" @click="handleEdit(row)">
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <el-button type="danger" size="small" @click="handleDelete(row)">
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 空数据状态 -->
      <div v-if="!loading && tableData.length === 0" class="empty-state">
        <el-empty description="暂无货品数据">
          <el-button type="primary" @click="fetchGoodList">
            <el-icon><Refresh /></el-icon>
            重新加载
          </el-button>
        </el-empty>
      </div>

      <!-- 分页 -->
      <div class="pagination-container" v-if="tableData.length > 0">
        <el-pagination
          v-model:current-page="pagination.pageIndex"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[8, 16, 32, 64]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增货品对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      title="新增货品"
      width="800px"
      :before-close="handleCloseAdd"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRules"
        label-width="120px"
        class="add-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="货品编码" prop="goodCode">
              <div class="code-input-group">
                <el-input v-model="addForm.goodCode" placeholder="自动生成货品编码" readonly />
                <el-button type="primary" @click="regenerateCode" size="small">
                  <el-icon><Refresh /></el-icon>
                  重新生成
                </el-button>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="货品名称" prop="goodName">
              <el-input v-model="addForm.goodName" placeholder="请输入货品名称" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="规格" prop="specification">
              <el-input v-model="addForm.specification" placeholder="请输入规格" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生产厂家" prop="company">
              <el-input v-model="addForm.company" placeholder="请输入生产厂家" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="供应商ID" prop="supplierId">
              <el-input-number v-model="addForm.supplierId" :min="1" placeholder="请输入供应商ID" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户ID" prop="customerId">
              <el-input-number v-model="addForm.customerId" :min="1" placeholder="请输入客户ID" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="进价" prop="rprice">
              <el-input-number v-model="addForm.rprice" :min="0" :precision="2" placeholder="请输入进价" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="售价" prop="cprice">
              <el-input-number v-model="addForm.cprice" :min="0" :precision="2" placeholder="请输入售价" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="货品状态" prop="goodState">
              <el-radio-group v-model="addForm.goodState" class="status-radio-group">
                <el-radio :value="1" class="status-radio">上架</el-radio>
                <el-radio :value="0" class="status-radio">下架</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseAdd">取消</el-button>
          <el-button type="primary" @click="handleSubmitAdd" :loading="addLoading">
            确定新增
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑货品对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑货品"
      width="800px"
      :before-close="handleCloseEdit"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editFormRules"
        label-width="120px"
        class="edit-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="货品编码" prop="goodCode">
              <el-input v-model="editForm.goodCode" placeholder="货品编码" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="货品名称" prop="goodName">
              <el-input v-model="editForm.goodName" placeholder="请输入货品名称" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="规格" prop="specification">
              <el-input v-model="editForm.specification" placeholder="请输入规格" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生产厂家" prop="company">
              <el-input v-model="editForm.company" placeholder="请输入生产厂家" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="供应商ID" prop="supplierId">
              <el-input-number v-model="editForm.supplierId" :min="1" placeholder="请输入供应商ID" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户ID" prop="customerId">
              <el-input-number v-model="editForm.customerId" :min="1" placeholder="请输入客户ID" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="进价" prop="rprice">
              <el-input-number v-model="editForm.rprice" :min="0" :precision="2" placeholder="请输入进价" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="售价" prop="cprice">
              <el-input-number v-model="editForm.cprice" :min="0" :precision="2" placeholder="请输入售价" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="货品状态" prop="goodState">
              <el-radio-group v-model="editForm.goodState" class="status-radio-group">
                <el-radio :value="1" class="status-radio">上架</el-radio>
                <el-radio :value="0" class="status-radio">下架</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseEdit">取消</el-button>
          <el-button type="primary" @click="handleSubmitEdit" :loading="editLoading">
            确定修改
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 货品详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="货品详情"
      width="900px"
      :before-close="handleCloseDetail"
    >
      <div v-if="currentDetailItem" class="detail-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="ID">
            <el-tag type="info" effect="dark">{{ currentDetailItem.id }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="货品编码">
            <el-tag type="primary" effect="dark">{{ currentDetailItem.goodCode }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="货品名称">
            <span class="detail-text">{{ currentDetailItem.goodName }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="规格">
            <span class="detail-text">{{ currentDetailItem.specification }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="生产厂家">
            <span class="detail-text">{{ currentDetailItem.company }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="货品状态">
            <el-tag :type="getStateTagType(currentDetailItem.goodState)" effect="dark">
              {{ getStateText(currentDetailItem.goodState) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="进价">
            <span class="price-text">¥{{ currentDetailItem.rprice }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="售价">
            <span class="price-text">¥{{ currentDetailItem.cprice }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="供应商ID">
            <el-tag type="warning" effect="plain">{{ currentDetailItem.supplierId }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="客户ID">
            <el-tag type="warning" effect="plain">{{ currentDetailItem.customerId }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="供应商名称">
            <span class="detail-text">{{ currentDetailItem.supplierName || '暂无' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="供应商等级">
            <span class="detail-text">{{ currentDetailItem.supplierLevel || '暂无' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="联系人">
            <span class="detail-text">{{ currentDetailItem.people || '暂无' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="联系电话">
            <span class="detail-text">{{ currentDetailItem.phone || '暂无' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="客户名称">
            <span class="detail-text">{{ currentDetailItem.customerName || '暂无' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="客户类型">
            <span class="detail-text">{{ currentDetailItem.customerType || '暂无' }}</span>
          </el-descriptions-item>
        </el-descriptions>
        
        <!-- 操作按钮 -->
        <div class="detail-actions">
          <el-button type="primary" @click="handleEditFromDetail">
            <el-icon><Edit /></el-icon>
            编辑货品
          </el-button>
          <el-button 
            :type="currentDetailItem.goodState === 1 ? 'warning' : 'success'" 
            @click="handleToggleStatusFromDetail"
          >
            <el-icon><Switch /></el-icon>
            {{ currentDetailItem.goodState === 1 ? '下架' : '上架' }}
          </el-button>
        </div>
      </div>
      
      <el-empty v-else description="未找到货品详情" />
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseDetail">关闭</el-button>
        </div>
      </template>
    </el-dialog>


  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Search, 
  Refresh, 
  Plus, 
  Download, 
  View, 
  Edit, 
  Delete,
  Switch,
  InfoFilled
} from '@element-plus/icons-vue'
import { getReadClient } from '@/Urls/AxiosHelper'

// 接口定义
interface GoodItem {
  id: number
  goodCode: string
  goodName: string
  goodState: number
  specification: string
  company: string
  supplierId: number
  customerId: number
  rprice: number
  cprice: number
  supplierCode: string
  supplierName: string
  supplierLevel: string
  people: string
  state: number
  phone: string
  desc: string
  customerCode: string
  customerName: string
  customerType: string
  userPeople: string
}

// 响应式数据
const loading = ref(false)
const tableData = ref<GoodItem[]>([])

// 新增货品相关
const addDialogVisible = ref(false)
const addLoading = ref(false)
const addFormRef = ref()

// 编辑货品相关
const editDialogVisible = ref(false)
const editLoading = ref(false)
const editFormRef = ref()
const currentEditItem = ref<GoodItem | null>(null)

// 详情相关
const detailDialogVisible = ref(false)
const currentDetailItem = ref<GoodItem | null>(null)


// 查询表单
const searchForm = reactive({
  goodName: '',
  goodState: null as number | null
})

// 新增货品表单
const addForm = reactive({
  goodCode: '',
  goodName: '',
  goodState: 1,
  specification: '',
  company: '',
  supplierId: null as number | null,
  customerId: null as number | null,
  rprice: null as number | null,
  cprice: null as number | null
})

// 编辑货品表单
const editForm = reactive({
  id: null as number | null,
  goodCode: '',
  goodName: '',
  goodState: 1,
  specification: '',
  company: '',
  supplierId: null as number | null,
  customerId: null as number | null,
  rprice: null as number | null,
  cprice: null as number | null
})

// 新增货品表单验证规则
const addFormRules = {
  goodCode: [
    { required: true, message: '请输入货品编码', trigger: 'blur' }
  ],
  goodName: [
    { required: true, message: '请输入货品名称', trigger: 'blur' }
  ],
  specification: [
    { required: true, message: '请输入规格', trigger: 'blur' }
  ],
  company: [
    { required: true, message: '请输入生产厂家', trigger: 'blur' }
  ],
  supplierId: [
    { required: true, message: '请输入供应商ID', trigger: 'blur' }
  ],
  customerId: [
    { required: true, message: '请输入客户ID', trigger: 'blur' }
  ],
  rprice: [
    { required: true, message: '请输入进价', trigger: 'blur' }
  ],
  cprice: [
    { required: true, message: '请输入售价', trigger: 'blur' }
  ],
  goodState: [
    { required: true, message: '请选择货品状态', trigger: 'change' }
  ]
}

// 编辑货品表单验证规则
const editFormRules = {
  goodName: [
    { required: true, message: '请输入货品名称', trigger: 'blur' }
  ],
  specification: [
    { required: true, message: '请输入规格', trigger: 'blur' }
  ],
  company: [
    { required: true, message: '请输入生产厂家', trigger: 'blur' }
  ],
  supplierId: [
    { required: true, message: '请输入供应商ID', trigger: 'blur' }
  ],
  customerId: [
    { required: true, message: '请输入客户ID', trigger: 'blur' }
  ],
  rprice: [
    { required: true, message: '请输入进价', trigger: 'blur' }
  ],
  cprice: [
    { required: true, message: '请输入售价', trigger: 'blur' }
  ],
  goodState: [
    { required: true, message: '请选择货品状态', trigger: 'change' }
  ]
}

// 分页数据
const pagination = reactive({
  pageIndex: 1,
  pageSize: 8,
  total: 0
})

// 获取货品列表
const fetchGoodList = async () => {
  try {
    loading.value = true

    // 尝试两种方式：代理和直接请求
    let response
    
    try {
      // 方式1：通过Vite代理
      const apiClient = getReadClient(0)
      const requestUrl = '/sellreadapi/api/Good/Goodlist'
      const requestParams = {
        pageindex: pagination.pageIndex,
        pagesize: pagination.pageSize,
        GoodName: searchForm.goodName || undefined,
        GoodState: searchForm.goodState !== null ? searchForm.goodState : undefined
      }
      
      response = await apiClient.get(requestUrl, {
        params: requestParams
      })
      
    } catch (proxyError) {
      // 方式2：直接请求API
      const directUrl = `http://localhost:5154/api/Good/Goodlist?pageindex=${pagination.pageIndex}&pagesize=${pagination.pageSize}${searchForm.goodName ? `&GoodName=${encodeURIComponent(searchForm.goodName)}` : ''}${searchForm.goodState !== null ? `&GoodState=${searchForm.goodState}` : ''}`
      
      const fetchResponse = await fetch(directUrl, {
        method: 'GET',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        }
      })
      
      if (!fetchResponse.ok) {
        throw new Error(`HTTP ${fetchResponse.status}: ${fetchResponse.statusText}`)
      }
      
      const data = await fetchResponse.json()
      response = { data, status: fetchResponse.status, headers: fetchResponse.headers }
    }

    // 处理API响应数据格式
    let goodsData = []
    let totalCount = 0

    if (response.data) {
      // 情况1：标准响应格式 {code: 200, data: {totalCount: 1, data: [...]}}
      if (response.data.code === 200 && response.data.data) {
        if (response.data.data.data && Array.isArray(response.data.data.data)) {
          // 嵌套结构：response.data.data.data
          goodsData = response.data.data.data
          totalCount = response.data.data.totalCount || response.data.data.data.length
        } else if (Array.isArray(response.data.data)) {
          // 直接数组：response.data.data
          goodsData = response.data.data
          totalCount = response.data.data.length
        } else if (response.data.data && typeof response.data.data === 'object') {
          // 单个对象：response.data.data
          goodsData = [response.data.data]
          totalCount = 1
        }
      }
      // 情况2：直接是数组
      else if (Array.isArray(response.data)) {
        goodsData = response.data
        totalCount = response.data.length
      }
      // 情况3：直接是对象（单个货品）
      else if (response.data.id || response.data.goodCode) {
        goodsData = [response.data]
        totalCount = 1
      }
    }

    tableData.value = goodsData
    pagination.total = totalCount
  } catch (error: any) {
    if (error.response) {
      ElMessage.error(`请求失败：${error.response.status} - ${error.response.data?.message || '服务器错误'}`)
    } else if (error.request) {
      ElMessage.error('网络连接失败，请检查服务器状态')
    } else {
      ElMessage.error(`请求失败：${error.message}`)
    }
    
    // 设置空数据
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 查询
const handleSearch = () => {
  pagination.pageIndex = 1
  fetchGoodList()
}

// 重置
const handleReset = () => {
  searchForm.goodName = ''
  searchForm.goodState = null
  pagination.pageIndex = 1
  fetchGoodList()
}

// 生成货品编码
const generateGoodCode = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hour = String(now.getHours()).padStart(2, '0')
  const minute = String(now.getMinutes()).padStart(2, '0')
  const second = String(now.getSeconds()).padStart(2, '0')
  const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0')
  
  return `G${year}${month}${day}${hour}${minute}${second}${random}`
}

// 重新生成编码
const regenerateCode = () => {
  addForm.goodCode = generateGoodCode()
  ElMessage.success('货品编码已重新生成')
}

// 新增
const handleAdd = () => {
  // 自动生成货品编码
  const autoGeneratedCode = generateGoodCode()
  
  // 重置表单
  Object.assign(addForm, {
    goodCode: autoGeneratedCode,
    goodName: '',
    goodState: 1,
    specification: '',
    company: '',
    supplierId: null,
    customerId: null,
    rprice: null,
    cprice: null
  })
  addDialogVisible.value = true
}

// 导出
const handleExport = () => {
  ElMessage.info('导出功能待实现')
}

// 关闭新增对话框
const handleCloseAdd = () => {
  console.log('手动关闭对话框')
  addDialogVisible.value = false
  // 重置表单验证
  if (addFormRef.value) {
    addFormRef.value.resetFields()
  }
}

// 提交新增货品
const handleSubmitAdd = async () => {
  try {
    // 表单验证
    if (!addFormRef.value) {
      ElMessage.error('表单引用不存在')
      return
    }
    
    await addFormRef.value.validate()
    addLoading.value = true
    
    // 准备提交数据
    const submitData = {
      GoodCode: addForm.goodCode,
      GoodName: addForm.goodName,
      GoodState: addForm.goodState,
      Specification: addForm.specification,
      Company: addForm.company,
      SupplierId: addForm.supplierId,
      CustomerId: addForm.customerId,
      Rprice: addForm.rprice,
      Cprice: addForm.cprice
    }
    
    // 调用API
    const response = await fetch('/sellwriteapi/api/Good/GoodAdd', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      body: JSON.stringify(submitData)
    })
    
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`)
    }
    
    const result = await response.json()
    
    if (response.ok && result.Code === 200) {
      ElMessage.success('货品新增成功！')
      addDialogVisible.value = false
      await fetchGoodList()
    } else {
      ElMessage.error(result.Message || '新增失败')
    }
    
  } catch (error: any) {
    if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {
      ElMessage.error('网络连接失败，请检查服务器状态')
    } else if (error.message.includes('HTTP')) {
      ElMessage.error(`服务器错误：${error.message}`)
    } else {
      ElMessage.error(`新增失败：${error.message}`)
    }
  } finally {
    addLoading.value = false
  }
}


// 查看详情
const handleDetail = (row: GoodItem) => {
  currentDetailItem.value = row
  detailDialogVisible.value = true
}

// 关闭详情对话框
const handleCloseDetail = () => {
  detailDialogVisible.value = false
  currentDetailItem.value = null
}

// 从详情页面编辑
const handleEditFromDetail = () => {
  if (currentDetailItem.value) {
    detailDialogVisible.value = false
    handleEdit(currentDetailItem.value)
  }
}

// 从详情页面切换状态
const handleToggleStatusFromDetail = () => {
  if (currentDetailItem.value) {
    console.log('从详情页面切换状态')
    // 关闭详情对话框
    detailDialogVisible.value = false
    // 调用状态切换功能
    handleToggleStatus(currentDetailItem.value)
  }
}

// 删除货品
const handleDelete = (row: GoodItem) => {
  console.log('=== 删除货品 ===')
  console.log('要删除的货品:', row)
  
  ElMessageBox.confirm(
    `确定要删除货品"${row.goodName}"吗？`,
    '删除确认',
    {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning',
      dangerouslyUseHTMLString: false
    }
  ).then(async () => {
    console.log('用户确认删除，开始删除流程')
    await deleteGood(row.id)
  }).catch(() => {
    console.log('用户取消删除')
  })
}

// 执行删除API调用
const deleteGood = async (id: number) => {
  try {
    console.log('🗑️ 开始删除货品，ID:', id)
    
    // 调用删除API
    const response = await fetch(`/sellwriteapi/api/Good/GoodDel?Id=${id}`, {
      method: 'GET',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      }
    })
    
    console.log('📡 删除API响应状态:', response.status, response.statusText)
    
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`)
    }
    
    const result = await response.json()
    console.log('📥 删除货品响应:', result)
    
    // 检查响应结果
    if (result.Code === 200) {
      console.log('✅ 删除成功')
      ElMessage.success('货品删除成功！')
      
      // 刷新列表
      await fetchGoodList()
      console.log('📋 删除后列表刷新完成')
    } else {
      console.log('❌ 删除失败，错误信息:', result.Message)
      ElMessage.error(result.Message || '删除失败')
    }
    
  } catch (error: any) {
    console.error('💥 删除货品失败:', error)
    console.error('🔍 错误类型:', error.name)
    console.error('📝 错误消息:', error.message)
    
    // 根据错误类型显示不同的错误信息
    if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {
      console.error('🌐 删除网络连接失败')
      ElMessage.error('网络连接失败，请检查服务器状态')
    } else if (error.message.includes('HTTP')) {
      console.error('🖥️ 删除服务器错误')
      ElMessage.error(`服务器错误：${error.message}`)
    } else {
      console.error('❓ 删除未知错误')
      ElMessage.error(`删除失败：${error.message}`)
    }
  }
}

// 切换状态
const handleToggleStatus = (row: GoodItem) => {
  const newStatus = row.goodState === 1 ? 0 : 1
  const statusText = newStatus === 1 ? '上架' : '下架'
  
  ElMessageBox.confirm(
    `确定要将货品"${row.goodName}"${statusText}吗？`,
    `${statusText}确认`,
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: newStatus === 1 ? 'success' : 'warning'
    }
  ).then(() => {
    // 模拟状态更新
    row.goodState = newStatus
    ElMessage.success(`${statusText}成功`)
    // 这里可以调用API更新状态
    // updateGoodStatus(row.id, newStatus)
  }).catch(() => {
    // 用户取消
  })
}

// 编辑
const handleEdit = (row: GoodItem) => {
  console.log('=== 开始编辑货品 ===')
  console.log('编辑的货品数据:', row)
  
  // 保存当前编辑项
  currentEditItem.value = row
  
  // 反填表单数据
  Object.assign(editForm, {
    id: row.id,
    goodCode: row.goodCode,
    goodName: row.goodName,
    goodState: row.goodState,
    specification: row.specification,
    company: row.company,
    supplierId: row.supplierId,
    customerId: row.customerId,
    rprice: row.rprice,
    cprice: row.cprice
  })
  
  console.log('反填后的编辑表单:', editForm)
  
  // 打开编辑对话框
  editDialogVisible.value = true
}

// 关闭编辑对话框
const handleCloseEdit = () => {
  console.log('关闭编辑对话框')
  editDialogVisible.value = false
  // 重置表单验证
  if (editFormRef.value) {
    editFormRef.value.resetFields()
  }
}

// 提交编辑货品
const handleSubmitEdit = async () => {
  console.log('=== 开始编辑货品流程 ===')
  console.log('当前编辑表单数据:', editForm)
  
  try {
    // 表单验证
    if (!editFormRef.value) {
      console.error('编辑表单引用不存在')
      ElMessage.error('编辑表单引用不存在')
      return
    }
    
    console.log('开始编辑表单验证...')
    await editFormRef.value.validate()
    console.log('✅ 编辑表单验证通过')
    
    editLoading.value = true
    console.log('设置编辑加载状态为 true')
    
    // 准备提交数据
    const submitData = {
      Id: editForm.id,
      GoodCode: editForm.goodCode,
      GoodName: editForm.goodName,
      GoodState: editForm.goodState,
      Specification: editForm.specification,
      Company: editForm.company,
      SupplierId: editForm.supplierId,
      CustomerId: editForm.customerId,
      Rprice: editForm.rprice,
      Cprice: editForm.cprice
    }
    
    console.log('📤 提交编辑货品数据:', submitData)
    
    // 调用API（使用相对路径，通过Vite代理）
    console.log('🌐 开始编辑API调用...')
    const response = await fetch('/sellwriteapi/api/Good/GoodUpdate', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      body: JSON.stringify(submitData)
    })
    
    console.log('📡 编辑API响应状态:', response.status, response.statusText)
    console.log('📡 编辑响应头:', Object.fromEntries(response.headers.entries()))
    
    if (!response.ok) {
      console.error('❌ 编辑HTTP错误:', response.status, response.statusText)
      throw new Error(`HTTP ${response.status}: ${response.statusText}`)
    }
    
    const result = await response.json()
    console.log('📥 编辑货品响应:', result)
    
    // 详细检查响应状态和内容
    console.log('🔍 检查编辑响应条件:')
    console.log('  - response.ok:', response.ok)
    console.log('  - result.Code:', result.Code)
    console.log('  - result.Message:', result.Message)
    console.log('  - result.Data:', result.Data)
    
    // 修复：使用正确的大写字段名
    if (response.ok && result.Code === 200) {
      console.log('✅ 编辑成功，准备关闭对话框')
      ElMessage.success('货品编辑成功！')
      
      // 使用 nextTick 确保 DOM 更新
      await nextTick()
      
      // 关闭对话框
      editDialogVisible.value = false
      console.log('🔒 编辑对话框关闭状态:', editDialogVisible.value)
      
      // 刷新列表
      await fetchGoodList()
      console.log('📋 编辑后列表刷新完成')
    } else {
      console.log('❌ 编辑失败，错误信息:', result.Message)
      console.log('❌ 编辑失败原因 - response.ok:', response.ok, 'result.Code:', result.Code)
      ElMessage.error(result.Message || '编辑失败')
    }
    
  } catch (error: any) {
    console.error('💥 编辑货品失败:', error)
    console.error('🔍 错误类型:', error.name)
    console.error('📝 错误消息:', error.message)
    console.error('📚 错误堆栈:', error.stack)
    
    // 根据错误类型显示不同的错误信息
    if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {
      console.error('🌐 编辑网络连接失败')
      ElMessage.error('网络连接失败，请检查服务器状态')
    } else if (error.message.includes('HTTP')) {
      console.error('🖥️ 编辑服务器错误')
      ElMessage.error(`服务器错误：${error.message}`)
    } else {
      console.error('❓ 编辑未知错误')
      ElMessage.error(`编辑失败：${error.message}`)
    }
  } finally {
    console.log('🏁 完成编辑流程，重置加载状态')
    editLoading.value = false
  }
}


// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.pageIndex = 1
  fetchGoodList()
}

// 当前页改变
const handleCurrentChange = (page: number) => {
  pagination.pageIndex = page
  fetchGoodList()
}

// 获取状态标签类型
const getStateTagType = (state: number) => {
  return state === 1 ? 'success' : 'info'
}

// 获取状态文本
const getStateText = (state: number) => {
  return state === 1 ? '上架' : '下架'
}


// 组件挂载时获取数据
onMounted(() => {
  fetchGoodList()
})
</script>

<style scoped>
.goodshow-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 20px;
  text-align: center;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 28px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 16px;
}

.search-card,
.action-card,
.table-card {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 0;
}

.action-buttons {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.action-buttons .el-button {
  border-radius: 6px;
  font-weight: 500;
}

.price-text {
  color: #e6a23c;
  font-weight: 600;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.empty-state {
  padding: 40px 20px;
  text-align: center;
}

.empty-state .el-empty {
  padding: 20px;
}

.empty-state .el-button {
  margin: 8px;
}

/* 新增对话框样式 */
.add-form {
  padding: 20px 0;
}

.add-form .el-form-item {
  margin-bottom: 20px;
}

.add-form .el-input,
.add-form .el-select,
.add-form .el-input-number {
  width: 100%;
}

/* 编辑对话框样式 */
.edit-form {
  padding: 20px 0;
}

.edit-form .el-form-item {
  margin-bottom: 20px;
}

.edit-form .el-input,
.edit-form .el-select,
.edit-form .el-input-number {
  width: 100%;
}

/* 详情对话框样式 */
.detail-content {
  padding: 20px 0;
}

.detail-text {
  font-weight: 500;
  color: #303133;
}

.price-text {
  color: #e6a23c;
  font-weight: 600;
  font-size: 16px;
}

.detail-actions {
  margin-top: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 8px;
  text-align: center;
}

.detail-actions .el-button {
  margin: 0 8px;
}

.dialog-footer {
  text-align: right;
}

.dialog-footer .el-button {
  margin-left: 10px;
}

/* 编码输入组样式 */
.code-input-group {
  display: flex;
  gap: 8px;
  align-items: center;
}

.code-input-group .el-input {
  flex: 1;
}

.code-input-group .el-button {
  flex-shrink: 0;
}

/* 状态单选框样式 */
.status-radio-group {
  display: flex;
  gap: 20px;
}

.status-radio {
  margin-right: 0;
}

.status-radio .el-radio__label {
  font-weight: 500;
  color: #606266;
}

.status-radio.is-checked .el-radio__label {
  color: #409eff;
  font-weight: 600;
}


/* 响应式设计 */
@media (max-width: 768px) {
  .goodshow-container {
    padding: 10px;
  }
  
  .search-form {
    flex-direction: column;
  }
  
  .search-form .el-form-item {
    margin-right: 0;
    margin-bottom: 10px;
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  .action-buttons .el-button {
    width: 100%;
  }
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #303133;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-table .el-table__row:hover) {
  background-color: #f5f7fa;
}

/* 卡片样式优化 */
:deep(.el-card) {
  border-radius: 12px;
  border: 1px solid #e4e7ed;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

:deep(.el-card__header) {
  background-color: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
  padding: 16px 20px;
}

:deep(.el-card__body) {
  padding: 20px;
}

/* 按钮样式优化 */
:deep(.el-button) {
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.3s ease;
}

:deep(.el-button:hover) {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 状态标签样式优化 */
:deep(.el-tag--success) {
  background-color: #67c23a;
  border-color: #67c23a;
  color: white;
}

:deep(.el-tag--info) {
  background-color: #909399;
  border-color: #909399;
  color: white;
}

:deep(.el-tag--success.is-dark) {
  background-color: #67c23a;
  border-color: #67c23a;
  color: white;
}

:deep(.el-tag--info.is-dark) {
  background-color: #909399;
  border-color: #909399;
  color: white;
}

/* 分页样式优化 */
:deep(.el-pagination) {
  justify-content: center;
}

:deep(.el-pagination .el-pager li) {
  border-radius: 6px;
  margin: 0 2px;
}

:deep(.el-pagination .el-pager li.is-active) {
  background-color: #409eff;
  color: white;
}
</style>